package com.example.project44
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.cardgame.model.CardMatchingGame
val game :CardMatchingGame = CardMatchingGame(24)
class GameActivity : ComponentActivity(){
        lateinit var adapter: CardAdapter
        @Suppress("MissingInflatedId")
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_game)

            val recyclerView:RecyclerView = findViewById(R.id.recyclerView)
            adapter = CardAdapter(game)

            recyclerView.adapter = adapter
            val configure = resources.configuration
            if(configure.orientation == Configuration.ORIENTATION_PORTRAIT){
                recyclerView.layoutManager = GridLayoutManager(this,4)
            }else {
                recyclerView.layoutManager = GridLayoutManager(this, 6)
            }
            adapter.setOnClickListener {
                game.chooseCardAtIndex(it,3)
                updateUI()
            }
            updateUI()
            findViewById<Button>(R.id.button_reset).setOnClickListener {
                game.reset()
                updateUI()
            }
            findViewById<Button>(R.id.button_back).setOnClickListener {
                val finalScore = game.score
                val data = Intent().apply {
                    putExtra("score", finalScore)
                }
                setResult(RESULT_OK, data)
                finish()
            }
        }

        private fun updateUI() {
            adapter.notifyDataSetChanged()
            val score = findViewById<TextView>(R.id.textView)
            score.text = getString(R.string.text) + game.score.toString()
        }
    }